<template>
  <Modal v-model:visible="showModal" title="燃气概况" width="90vw">
    <div class="flex flex-col w-full">
      <a-tabs v-model:activeKey="activeKey" size="small">
        <a-tab-pane key="1" tab="基本信息"></a-tab-pane>
        <a-tab-pane key="2" tab="商业用气量排名"></a-tab-pane>
      </a-tabs>

      <div class="flex flex-row items-center mb-1">
        <a-select
          v-model:value="searchParams.year"
          :options="utils.genSelectOptions('year')"
          @change="loadAllData"
        ></a-select>
      </div>

      <div v-show="activeKey === '1'" class="">
        <vxe-table
          :loading="true"
          v-bind="customTableStyle"
          :data="tableData"
          class="custom-vxe-table"
        >
          <vxe-column field="year" title="年份" width="80">
            <template #default="{ row }"> {{ row.year }}年 </template>
          </vxe-column>
          <vxe-column field="month" title="月份" width="80" :sortable="true">
            <template #default="{ row }"> {{ row.month }}月 </template>
          </vxe-column>
          <vxe-column field="residentNum" title="居民用户数(户)" minWidth="100" :sortable="true">
            <template #default="{ row }"> {{ row.residentNum }} </template>
          </vxe-column>
          <vxe-column
            field="residentUseGasVolume"
            title="居民用气量（万方）"
            minWidth="140"
            :sortable="true"
          >
            <template #default="{ row }">
              {{ row.residentUseGasVolume ? row.residentUseGasVolume.toFixed(2) + '%' : '/' }}
            </template>
          </vxe-column>
          <vxe-column field="businessNum" title="商业用户数(户)" minWidth="100" :sortable="true">
            <template #default="{ row }"> {{ row.businessNum }} </template> </vxe-column
          >x
          <vxe-column
            field="businessUseGasVolume"
            title="商业用气量（万方）"
            minWidth="140"
            :sortable="true"
          >
            <template #default="{ row }">
              {{ row.businessUseGasVolume ? row.businessUseGasVolume.toFixed(2) + '%' : '/' }}
            </template>
          </vxe-column>
          <vxe-column
            field="businessUseGasVolumeTb"
            title="商业用气量同比增幅"
            minWidth="140"
            :sortable="true"
          >
            <template #default="{ row }">
              {{ row.businessUseGasVolumeTb ? row.businessUseGasVolumeTb.toFixed(2) + '%' : '/' }}
            </template>
          </vxe-column>
          <vxe-column
            field="businessUseGasVolumeHb"
            title="商业用气量环比增幅"
            minWidth="140"
            :sortable="true"
          >
            <template #default="{ row }">
              {{
                row.businessUseGasVolumeHb ? row.businessUseGasVolumeHb.toFixed(2) + '%' : '/'
              }}</template
            >
          </vxe-column>
          <!--          <vxe-column field="productionTotal" title="生产总量（方）" minWidth="140" :sortable="true">-->
          <!--            <template #default="{ row }"> {{ row.productionTotal.toFixed(3) }}万 </template>-->
          <!--          </vxe-column>-->
          <vxe-column
            field="supplyGasTotal"
            title="供气总量（万方）"
            minWidth="140"
            :sortable="true"
          >
            <template #default="{ row }">
              {{ row.supplyGasTotal ? row.supplyGasTotal.toFixed(2) + '%' : '/' }}
            </template>
          </vxe-column>
          <vxe-column
            field="supplyGasTotalTb"
            title="供气总量同比增幅"
            minWidth="140"
            :sortable="true"
          >
            <template #default="{ row }">
              {{ row.supplyGasTotalTb ? row.supplyGasTotalTb.toFixed(2) + '%' : '/' }}
            </template>
          </vxe-column>
          <vxe-column
            field="supplyGasTotalHb"
            title="供气总量环比增幅"
            minWidth="140"
            :sortable="true"
          >
            <template #default="{ row }">
              {{ row.supplyGasTotalHb ? row.supplyGasTotalHb.toFixed(2) + '%' : '/' }}</template
            >
          </vxe-column>
        </vxe-table>
      </div>

      <div v-if="activeKey === '2'" class="">
        <vxe-table
          :loading="true"
          v-bind="customTableStyle"
          :data="tableData2"
          class="custom-vxe-table"
        >
          <vxe-column type="seq" title="序号" width="50"> </vxe-column>
          <vxe-column field="deptName" title="单位名称" minWidth="150" :sortable="true">
            <template #default="{ row }"> {{ row.deptName }} </template>
          </vxe-column>
          <vxe-column field="yearUseGasVolume" title="用气量(万方)" minWidth="120" :sortable="true">
            <template #default="{ row }">
              {{
                Number(row.yearUseGasVolume)
                  .toFixed(3)
                  .replace(/\.?0+$/, '')
              }}
            </template>
          </vxe-column>
          <vxe-column field="change" title="较上年" minWidth="100" :sortable="true">
            <template #default="{ row }">
              <span :class="row.change >= 0 ? 'text-green-500' : 'text-red-500'">
                {{ row.change >= 0 ? '+' : '' }}{{ row.change }}%
              </span>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </Modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import Modal from '@/components/modal.vue'
import { Apis } from '@/api'
import { message } from 'ant-design-vue'
import * as utils from '../../utils'
import dayjs from 'dayjs'

const isLoading = ref(false)

const showModal = ref(false)

const activeKey = ref('1')
const searchParams = ref({
  year: '',
  month: '',
})

const tableData = ref<any[]>([])
const tableData2 = ref<any[]>([])

// 统一管理表格样式
const customTableStyle = {
  ...utils.customTableStyle,
  footerMethod: ({ columns, data }) => {
    const footerData = [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return '合计'
        }
        if (
          [
            'residentUseGasVolume',
            'businessUseGasVolume',
            'productionTotal',
            'supplyGasTotal',
          ].includes(column.field)
        ) {
          return (utils.sumNum(data, column.field) || 0).toFixed(3) + '万'
        }

        return ''
      }),
    ]
    return footerData
  },
}

function loadAllData() {
  loadData()
  loadData2()
}

function loadData() {
  isLoading.value = true
  Apis.szbt.gasSurvey
    .get_list({
      params: {
        year: searchParams.value.year,
        pageNum: 1,
        pageSize: 20,
      },
    })
    .then((res) => {
      tableData.value = (res.rows || [])
        .filter((item) => item.year == searchParams.value.year)
        .sort((a: any, b: any) => {
          // 先按年份倒序
          if (b.month !== a.month) {
            return a.month - b.month
          }
        })
        .map((item: any, index: number) => {
          item.index = index + 1
          return item
        })
    })
    .catch((err) => {
      message.error('获取数据失败')
    })
    .finally(() => {
      isLoading.value = false
    })
}

function loadData2() {
  isLoading.value = true
  Apis.szbt.gasSurvey
    .get_getChartData({
      params: {
        year: searchParams.value.year,
        month: searchParams.value.month,
      },
    })
    .then((res) => {
      const arr = (res.topMap || []).sort(
        (a: any, b: any) => b.yearUseGasVolume - a.yearUseGasVolume,
      )

      tableData2.value = arr.map((item: any) => ({
        ...item,
        change: item.qnYearUseGasVolume
          ? (
              ((item.yearUseGasVolume || 0 - item.qnYearUseGasVolume) / item.qnYearUseGasVolume) *
              100
            ).toFixed(2)
          : 0,
      }))
    })
    .catch((err) => {
      message.error('获取数据失败')
    })
    .finally(() => {
      isLoading.value = false
    })
}

defineExpose({
  setData: (data: any) => {
    const { params } = data
    searchParams.value = params
    // tableData.value = data;
  },
  open: () => {
    showModal.value = true
    loadAllData()
  },
})
</script>

<style lang="scss" src="@/styles/custom-vxe-table.scss"></style>
